package com.lyf.boot.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.lyf.boot.properties.AuthProperties;
import com.lyf.boot.utils.AuthUtil;
import com.lyf.boot.utils.ServerUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * sa-token 配置
 * @author LuYufan
 * @date 2023/7/12 13:34
 */
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class SaTokenConfig implements WebMvcConfigurer {

    private final AuthProperties authProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {
                    StpUtil.checkLogin();
                    HttpServletRequest request = ServerUtil.request();
                    String headerCid = request.getHeader(AuthUtil.CLIENT_KEY);
                    String clientId = StpUtil.getExtra(AuthUtil.CLIENT_KEY).toString();
                    if(!StrUtil.equals(headerCid, clientId)){
                        throw NotLoginException.newInstance(StpUtil.getLoginType(),
                                "-100", "客户端ID与Token不匹配",
                                StpUtil.getTokenValue());
                    }
                }))
                .addPathPatterns("/**")
                .excludePathPatterns(authProperties.getApiWhiteList());
    }
}
